<?php
namespace admin\controllers;

use common\component\MenuHelper;
use common\component\Tree;
use common\models\Admin;
use common\models\AuthAssignment;
use common\models\Menu;
use common\models\User;
use common\service\DataService;
use common\models\AuthItem;
use common\service\MenuService;
use common\service\TreeService;
use Yii;
use admin\controllers\common\BaseController;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
use yii\rbac\Assignment;

/**
 * Site controller
 */
class AdminController extends BaseController
{
    /**
     * 管理员列表
     * @param string $uid
     * @return \yii\base\string
     */
    public function actionIndex()
    {
        return $this->view();
    }

    /**
     * 添加管理员
     */
    public function actionAdmin_add()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            //检测是否存在同名
            $check_admin = Admin::findByUsername($post['name']);
            if($check_admin){
                return $this->renderJSON([],'管理员名称已被使用,请更换',-1);
            }

            //检测是否存在相同手机号
            $check_phone = Admin::find()->where(['in','status',['1','2']])->andWhere(['phone'=>$post['phone']])->asArray()->one();
            if($check_phone){
                return $this->renderJSON([],'管理员手机号已被使用,请更换',-1);
            }

            $admin = new Admin();
            $admin->name = $post['name'];
            $admin->code = User::uniqueGuid();
            $admin->phone = $post['phone'];
            $admin->password = Admin::encryption($post['password'],$admin->code);
            $admin->status = $post['native'];
            $admin->created_at = time();

            if($admin->save(0)){
                return $this->renderJSON([],'管理员添加成功',200);
            }else{
                return $this->renderJSON($admin->errors,'管理员添加失败',-1);
            }
        }
        return $this->view();
    }

    /**
     * 编辑管理员
     */
    public function actionAdmin_edit()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            //获取对应的Admin
            $admin = Admin::findOne($post['id']);
            $admin->phone = $post['phone'];

            //如果有设置密码
            if(!empty($post['password'])){
                $admin->password = Admin::encryption($post['password'],$admin->code);
            }

            $admin->status = $post['native'];
            $admin->updated_at = time();

            if($admin->save(0)){
                return $this->renderJSON([],'管理员修改成功',200);
            }else{
                return $this->renderJSON($admin->errors,'管理员修改失败',-1);
            }
        }

        $id = $_GET['id'];
        $admin = Admin::findOne($id);
        $this->_data['admin'] = $admin;

        return $this->view();
    }

    /**
     *  分配角色
     */
    public function actionAdmin_assign()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $auth = Yii::$app->authManager;

            //如果传递了role_name执行下面
            if(isset($post['role_name']) && !empty($post['role_name'])){
                $connection = Yii::$app->db;
                $transaction = $connection->beginTransaction();
                try {

                    //先删除所有角色
                    if(!empty($post['id'])){
                        AuthAssignment::deleteAll(['user_id'=>$post['id']]);
                    }

                    //如果role_name参数是数组,循环指派角色
                    if(is_array($post['role_name'])){
                        foreach($post['role_name'] as $val)
                        {
                            $role =  $auth->getRole($val);
                            $auth->assign($role, $post['id']);
                        }
                    }

                    $transaction->commit();
                    return $this->renderJSON([],'角色指派成功',200);

                } catch (\Exception $e) {
                    $transaction->rollBack();
                    return $this->renderJSON($e->getMessage(),'角色指派失败',201);
                }

            }else{

                return $this->renderJSON([],'角色指派失败,请至少选择一个角色',201);
            }

        }

        $id = $_GET['id'];
        $admin = Admin::findOne($id);
        $auth = Yii::$app->authManager;
        $role_list = $auth->getRolesByUser($id);
        $this->_data['role_list'] = array_keys($role_list);
        $this->_data['roles'] = $auth->getRoles();
        $this->_data['admin'] = $admin;

        return $this->view();
    }


    /**
     * 删除管理员
     */
    public function actionAdmin_del()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            //获取对应的Admin
            $admin = Admin::findOne($post['id']);
            $admin->status = 3; //注销

            if($admin->save(0)){
                return $this->renderJSON([],'管理员删除成功',200);
            }else{
                return $this->renderJSON($admin->errors,'管理员删除失败',-1);
            }
        }
    }

    /**
     * 路由列表
     */
    public function actionRoute_list()
    {
        return $this->view();
    }

    /**
     * 角色列表
     */
    public function actionRole_list()
    {
        return $this->view();
    }

    /**
     * 菜单列表
     */
    public function actionMenu()
    {
        return $this->view();
    }

    /**
     *  添加角色
     */
    public function actionRole_add()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            $connection = Yii::$app->db;
            $transaction = $connection->beginTransaction();
            try {

                //添加角色
                $auth = Yii::$app->authManager;
                $role = $auth->createRole($post['name']);
                $auth->add($role);

                //循环添加权限
                if(isset($post['authids']) && !empty($post['authids'])){
                    $list = array_filter($post['authids']);
                    foreach($list as $val)
                    {
                        $item = $auth->getPermission($val);
                        if($item){
                            $auth->addChild($role, $item);
                        }
                    }
                }

                $transaction->commit();
                return $this->renderJSON([],'角色添加成功',200);

            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->renderJSON($e->getMessage(),'角色添加失败',201);
            }





        }
        return $this->view();
    }

    /**
     *  编辑角色
     */
    public function actionRole_edit()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            $connection = Yii::$app->db;
            $transaction = $connection->beginTransaction();
            try {
                //获取角色
                $auth = Yii::$app->authManager;
                $role = $auth->getRole($post['name']);

                //删除角色所有权限
                $auth->removeChildren($role);

                //再循环添加权限
                if(isset($post['authids']) && !empty($post['authids'])){
                    //获得目前需要添加进去的权限
                    $list = array_filter($post['authids']);
                    foreach($list as $val)
                    {
                        $item = $auth->getPermission($val);
                        if($item){
                            $auth->addChild($role, $item);
                        }
                    }
                }

                $transaction->commit();
                return $this->renderJSON([],'角色修改成功',200);

            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->renderJSON($e->getMessage(),'角色修改失败',201);
            }


        }

        //获取角色名称
        $this->_data['name'] = $_GET['name'];
        return $this->view();
    }


    /**
     * 删除角色
     */
    public function actionRole_del()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $name = $post['name'];

            //权限方法
            $auth = Yii::$app->authManager;

            //获取角色的对应用户
            $users = $auth->getUserIdsByRole($post['name']);
            if(!empty($users)){
                return $this->renderJSON([],'该角色已经分配给用户,不能删除。',-1);
            }

            //如果走到这一步,说明没有分配给用户,执行删除
            $role = $auth->getRole($post['name']);
            if($auth->remove($role)){
                return $this->renderJSON([],'角色删除成功',200);
            }else{
                return $this->renderJSON([],'角色删除失败',-1);
            }
        }
    }


    /**
     * 菜单添加
     */
    public function actionMenu_add()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $menu = new Menu();
            $menu->setAttributes($post,false);
            $menu->scenario = 'backend';
            if($menu->save(0)){

                //改变权限节点
                Menu::Change_menu($post['url'],$post['is_display']);

                return $this->renderJSON([],'菜单添加成功',200);
            }else{
                return $this->renderJSON($menu->errors,'菜单添加失败',-1);
            }
        }

        $menu_list = Menu::getMenusName('','is_display = 1');
        $this->_data['menu_list'] = $menu_list;

        return $this->view();
    }

    /**
     * 菜单添加
     */
    public function actionSet_menu()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $menu = new Menu();
            $menu->setAttributes($post,false);
            $menu->scenario = 'backend';
            if($menu->save(0)){
                return $this->renderJSON([],'菜单添加成功',200);
            }else{
                return $this->renderJSON($menu->errors,'菜单添加失败',-1);
            }
        }

        $menu_list = Menu::getMenusName('','is_display = 1');
        $this->_data['menu_list'] = $menu_list;
        $this->_data['name'] = $_GET['name'];

        return $this->view();
    }

    /**
     * 菜单修改
     */
    public function actionMenu_edit()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $menu = Menu::findOne($post['id']);
            $menu->setAttributes($post,false);
            $menu->scenario = 'backend';
            if($menu->save(0)){
                //改变权限节点
                Menu::Change_menu($post['url'],$post['is_display']);
                return $this->renderJSON([],'菜单修改成功',200);
            }else{
                return $this->renderJSON($menu->errors,'菜单修改失败',-1);
            }
        }

        $menu_list = Menu::getMenusName('','is_display = 1');
        $this->_data['menu_list'] = $menu_list;

        $id = $_GET['id'];
        $this->_data['menu'] = Menu::findOne($id);

        return $this->view();
    }

    /**
     *  菜单删除
     *
     */
    public function actionMenu_del()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $menu = Menu::findOne($post['id']);

            if($menu->delete()){
                return $this->renderJSON([],'菜单删除成功',200);
            }else{
                return $this->renderJSON($menu->errors,'菜单删除失败',-1);
            }
        }
    }

    //获取用户数据列表
    public function actionGet_list_data()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            $limit = Yii::$app->request->post('limit',10);
            $page = Yii::$app->request->post('page',0);

            $user_list = Admin::find()->indexBy('id')->asArray()->all();

            $data = new DataService(new Admin());

            $condition = 'status <> 3';

            if(!empty($post['start_time']))
            {
                $condition .= ' and created_at >= "'.strtotime($post['start_time'].' 00:00:00').'"';
            }

            if(!empty($post['end_time']))
            {
                $condition .= ' and created_at < "'.strtotime($post['end_time'].' 23:59:59').'"';
            }

            if(!empty($post['keyword']))
            {
                if(is_numeric($post['keyword'])){
                    $condition .= ' and ( id = "'.$post['keyword'].'" or firm_id = "'.$post['keyword'].'") ';
                }else{
                    $condition .= ' and name like "%'.$post['keyword'].'%"';
                }
            }

            //数据返回
            $res = $data->getDataByCondition($condition,$limit,$page-1,'','created_at desc',true);

            //数据重新拼接返回
            $arr = [];
            foreach($res['data'] as $key=>$val)
            {
                $arr[$key] = $val;
                $arr[$key]['firm_id'] = $val['firm_id'] == 0 ? '未绑定' : $val['firm_id'];
                $arr[$key]['status'] = Admin::getStatusText($val['status']);
                $arr[$key]['int_id'] = $user_list[$val['int_id']]['name'];
                $arr[$key]['created_at'] = date('Y-m-d H:i:s',$val['created_at']);
            }

            if($res){
                echo json_encode([
                    'code'=>0,
                    'count'=>$res['count'],
                    'data'=>$arr,
                    'extra'=>'',
                    'message'=>'获取数据成功'
                ]);
            }
        }
    }

    /**
     * 获取路由列表数据
     */
    public function actionGet_route_list_data()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            $limit = $this->post('limit',20);
            $page = $this->post('page','0');

            $data = new DataService(new AuthItem());
            $condition = ' type = 2 ';

            if(!empty($post['keyword'])){
                $condition .= ' AND name like "%'.$post['keyword'].'%"';
            }

            $result = $data->getDataByCondition($condition,$limit,$page-1,'','created_at desc',true);

            $arr = [];
            foreach($result['data'] as $key=>$val)
            {
                $arr[$key] = $val;
                $arr[$key]['type'] = $val['type'] == 1 ? '角色' : '路由链接';
                $arr[$key]['is_menu'] = Menu::MenuSetList[$val['is_menu']];
                $arr[$key]['created_at'] = date('Y-m-d H:i:s',$val['created_at']);
                $arr[$key]['updated_at'] = date('Y-m-d H:i:s',$val['updated_at']);
            }

            if($result){

                return json_encode([
                    'code'=>0,
                    'msg'=>'数据返回成功',
                    'count'=>$result['count'],
                    'data'=>$arr
                ]);

            }else{

                return json_encode([
                    'code'=>-1,
                    'msg'=>'数据返回成功',
                    'count'=>0,
                    'data'=>[]
                ]);

            }
        }
    }


    /**
     * 获取角色列表数据
     */
    public function actionGet_role_list_data()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            $limit = $this->post('limit',20);
            $page = $this->post('page','0');

            $data = new DataService(new AuthItem());
            $condition = ' type = 1 ';

            if(!empty($post['keyword'])){
                $condition .= ' AND name like "%'.$post['keyword'].'%"';
            }

            $result = $data->getDataByCondition($condition,$limit,$page-1,'','created_at desc',true);

            $arr = [];
            foreach($result['data'] as $key=>$val)
            {
                $arr[$key] = $val;
                $arr[$key]['type'] = $val['type'] == 1 ? '角色' : '路由链接';
                $arr[$key]['created_at'] = date('Y-m-d H:i:s',$val['created_at']);
                $arr[$key]['updated_at'] = date('Y-m-d H:i:s',$val['updated_at']);
            }

            if($result){

                return json_encode([
                    'code'=>0,
                    'msg'=>'数据返回成功',
                    'count'=>$result['count'],
                    'data'=>$arr
                ]);

            }else{

                return json_encode([
                    'code'=>-1,
                    'msg'=>'数据返回成功',
                    'count'=>0,
                    'data'=>[]
                ]);

            }
        }
    }

    /**
     * 获取菜单列表数据
     */
    public function actionGet_menu_list_data()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            $condition = '1=1';
            if(!empty($post['show']) && $post['show']=='on'){
                $condition .= ' AND is_display = 1 ';
            }

            $menu_list = Menu::getMenus('',$condition);
            $menu_names = Menu::getMenusName();

            $arr = [];
            foreach($menu_list as $key=>$val)
            {
                $arr[$key] = $val;
                $arr[$key]['name'] = $menu_names[$val['id']];
                $arr[$key]['type'] = $val['type'] == 0 ? '后台菜单' : '前台菜单';
                $arr[$key]['is_display'] = $val['is_display'] == 1 ? '菜单' : '权限节点';
                $arr[$key]['created_at'] = date('Y-m-d H:i:s',$val['created_at']);
                $arr[$key]['updated_at'] = date('Y-m-d H:i:s',$val['updated_at']);
            }


            return json_encode([
                'code'=>0,
                'msg'=>'数据返回成功',
                'count'=>count($arr),
                'data'=>$arr
            ]);

        }
    }

    /**
     * 路由表信息修改
     */
    public function actionEdit_route()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $model = AuthItem::find()->where(['name'=>$post['name']])->one();
            $model->description = $post['description'];
            if(!$model->save(0)){
                return $this->renderJSON($model->getFirstErrors(),'修改失败',-1);
            }
            return $this->renderJSON([],'修改成功',0);
        }
    }


    /**
     *   获取所有权限节点数据
     *   {
            "code": 0,
            "msg": "获取成功",
            "data": {"trees":[
                {"name": "用户管理", "value": "xsgl", "checked": true},
                {"name": "用户组管理", "value": "sbgl", "checked": true,
                 "list": [
                    {"name": "角色管理", "value": "sbgl-sbsjlb", "checked": true,
                        "list":[
                            {"name": "添加角色", "value": "sbgl-sbsjlb-dj", "checked": true},
                            {"name": "角色列表", "value": "sbgl-sbsjlb-yl", "checked": false}
                        ]},
                    {"name": "管理员管理", "value": "sbgl-sbsjlb", "checked": true,
                        "list":[
                            {"name": "添加管理员", "value": "sbgl-sbsjlb-dj", "checked": true},
                            {"name": "管理员列表", "value": "sbgl-sbsjlb-yl", "checked": false}
                        ]}
                ]}]
     *     }
     *   }
     *
     */
    public function actionGet_auth_list()
    {
        //根据角色名称获取所有权限
        if($this->_isGet()){
            $name = $this->get('name');
            $auth = Yii::$app->authManager;
            $list = $auth->getChildren($name);
            $auth_arr = array_keys($list);
        }

        $menu_list = Menu::getMenus();
        $menu_list = ArrayHelper::index($menu_list,'id');

        $arr = [];
        foreach($menu_list as $key=>$val)
        {
            $arr[$key]['name'] = $val['name'];
            $arr[$key]['value'] = $val['url'];
            $arr[$key]['id'] = $val['id'];
            $arr[$key]['parent_id'] = $val['parent_id'];
            if(in_array($val['url'],$auth_arr)){
                $arr[$key]['checked'] = true;
                $arr[$val['parent_id']]['checked'] = true;
            }else{
                $arr[$key]['checked'] = false;
            }
        }

        $arr2 = TreeService::makeTree($arr,['parent_key'=>'parent_id','children_key'=>'list']);
        echo json_encode([
            "code"  =>  0,
            "msg"   =>  "获取成功",
            "data"  =>  [
                "trees" =>  $arr2
            ]
        ]);

    }


}
